package org.jflame.context.spring.aop;

import org.jflame.commons.reflect.ReflectionHelper;
import org.jflame.commons.util.ArrayHelper;
import org.jflame.commons.util.StringHelper;

import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class KeyExprParseContext {

    private Set<KeyExprParser> parsers = new HashSet<>();
    private static SpelKeyParser seplKeyParser = new SpelKeyParser();

    private KeyExprParser defaultParser = new KeyExprParser() {

        @Override
        public boolean support(String keyExpression) {
            return true;
        }

        @Override
        public String parse(String key, final Method method, final Object[] methodArgs) {
            return ReflectionHelper.toSignatureString(method);
        }
    };

    public KeyExprParseContext() {
        parsers.add(seplKeyParser);
    }

    /**
     * 提取请求唯一标识id
     * 
     * @param key
     * @param joinPoint aop切入点
     * @return
     */
    public String parse(final String key, final Method method, final Object[] methodArgs) {
        String rid = null;
        if (StringHelper.isNotEmpty(key)) {
            for (KeyExprParser requestIdExtracter : parsers) {
                if (requestIdExtracter.support(key)) {
                    rid = requestIdExtracter.parse(key, method, methodArgs);
                    break;
                }
            }
            if (rid == null) {
                rid = key;
            }
        } else {
            rid = defaultParser.parse(key, method, methodArgs);
        }
        return rid;
    }

    public void addParsers(KeyExprParser... _parsers) {
        if (ArrayHelper.isNotEmpty(_parsers)) {
            Collections.addAll(this.parsers, _parsers);
        }
    }

    /**
     * 设备新的默认解析器
     * 
     * @param defaultParser
     */
    public void setDefaultParser(KeyExprParser defaultParser) {
        this.defaultParser = defaultParser;
    }

}
